#region Copyright
/// <copyright>
/// Copyright (c) 2007 Ilia Shramko.
/// Released under the terms of the GNU General Public License.
/// </copyright>
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;

namespace Osh.ProgDvb
{
	public class Settings
	{
		#region Sections
		private class OptionsSection
		{
			public static string SectionName = "Options";
		}

		private class AVManagerSection
		{
			public static string SectionName = "AVManager";
			public string[] RecordFolders;
		}
		#endregion Sections

		#region NativeMethods
		private class NativeMethods
		{
			[DllImport("kernel32.dll")]
			public static extern uint GetPrivateProfileString(string lpAppName,
				string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);
		}
		#endregion NativeMethods

		private static string ProgDvbIniFile = "ProgDVB.ini";

		private ProgDvbApplication _progDvb;
		private string _path;
		private FileSystemWatcher _fileWatcher;

		private OptionsSection _options;
		private AVManagerSection _avManager;

		internal Settings(ProgDvbApplication progDvb, string progDvbFolder)
		{
			if(progDvb == null)
				throw new ArgumentNullException("progDvb");
			if(progDvbFolder == null)
				throw new ArgumentNullException("progDvbFolder");

			Init();

			_progDvb = progDvb;
			_path = Path.Combine(progDvbFolder, ProgDvbIniFile);
			_fileWatcher = new FileSystemWatcher(progDvbFolder, ProgDvbIniFile);
			_fileWatcher.NotifyFilter = NotifyFilters.LastWrite;
			_fileWatcher.Changed += new FileSystemEventHandler(FileWatcher_Changed);
			_fileWatcher.EnableRaisingEvents = true;
		}

		private void FileWatcher_Changed(object sender, FileSystemEventArgs e)
		{
			Init();
			_progDvb.OnSettingsChanged();
		}

		private void Init()
		{
			_options = new OptionsSection();
			_avManager = new AVManagerSection();
		}

		public string GetRecordFolder()
		{
			string[] recordFolders = this.RecordFolders;
			if(recordFolders.Length > 0)
				return recordFolders[0];
			return null;
		}

		public string[] RecordFolders
		{
			get
			{
				if(_avManager.RecordFolders == null)
				{
					List<string> folders = new List<string>();

					for(int i = 0; i < 3; i++)
					{
						StringBuilder sb = new StringBuilder(500);

						string keyName = (i == 0 ? "RecordDir" : ("RecordDir" + i));
						uint res = NativeMethods.GetPrivateProfileString(AVManagerSection.SectionName,
							keyName, string.Empty, sb, sb.Capacity, _path);

						if(sb.Length > 0)
							folders.Add(sb.ToString());
					}

					_avManager.RecordFolders = folders.ToArray();
				}
				return _avManager.RecordFolders;
			}
		}
	}
}
